package org.bigk.invoices.actions.login;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.bigk.invoices.Globals;
import org.bigk.invoices.actions.InvoicesActionSupport;
import org.bigk.invoices.exceptions.ServiceException;
import org.bigk.invoices.model.User;
import org.bigk.invoices.services.LoginService;

public class Login extends InvoicesActionSupport
		implements SessionAware {
	
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(Login.class);

	private static final long serialVersionUID = -1032058474470861737L;

	private Map<String, Object> session;
	private String username;
	private String password;
	
	private LoginService loginService;

	@SkipValidation
	public String input() {
		return INPUT;
	}
	
	public String execute() {
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start");
		}

		String result = null;
		
		User user = null;
		try {
			user = loginService.processLogin(username, password);
			result = SUCCESS;
			
		} catch (ServiceException ex) {
			logger.error("execute()", ex);
			this.addActionError(ex);
			result = INPUT;
		}
		
		if (user != null) {
			session.put(Globals.SP_LOGGED_FLAG, Boolean.TRUE);
			session.put(Globals.SP_USER, user);
		} else {
			session.clear();
			session.put(Globals.SP_LOGGED_FLAG, Boolean.FALSE);
		}
		
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - end - return value=" + result);
		}
		return result;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
}
